<template>
  <canvas class="webgl" ref="containerRef"></canvas>

  <MoreInfo>
    <p>PBR(physically based rendering)</p>
    <p>UV coordinates</p>
    <p>图片越小越好(webp)</p>
    <p>png 无损</p>
    <el-divider></el-divider>
    <p>纹理网址：</p>

    <el-link href="https://www.poliigon.com/" type="primary" target="_blank">https://www.poliigon.com/</el-link>
    <el-link href="https://3dtextures.me/" type="primary" target="_blank">https://3dtextures.me/</el-link>
    <el-link href="https://www.arroway-textures.ch/" type="primary" target="_blank">https://www.arroway-textures.ch/</el-link>
  </MoreInfo>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useThree } from '@/hooks/use-three-hook'
import MoreInfo from '@/components/MoreInfo.vue'
import { AmbientLight, BoxGeometry, Mesh, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial } from 'three'
// import HighlightJS from '@/components/HighlightJS.vue'

const containerRef = ref<HTMLCanvasElement | null>(null)
const { gui, scene, camera, addAnimationCallback } = useThree(containerRef)

let cube: Mesh
const params = {
  type: 'MeshBasicMaterial',
  color: 0x00ff00
}

onMounted(() => {
  if (scene.value && camera.value) {
    const box = new BoxGeometry(1, 1, 1)
    const material = new MeshBasicMaterial({ color: 0x00ff00 })
    cube = new Mesh(box, material)
    scene.value.add(cube)
    const light = new AmbientLight( 0x404040 ) // 柔和的白光
    scene.value.add( light )

    gui
      .add(params, 'type', ['MeshBasicMaterial', 'MeshLambertMaterial', 'MeshPhongMaterial'])
      .name('材质类型')
      .onChange((v) => {
        if (Array.isArray(cube.material)) {
          cube.material.forEach((m) => {
            m.dispose()
          })
        } else {
          cube.material.dispose()
        }

        if (v === 'MeshBasicMaterial') {
          cube.material = new MeshBasicMaterial({ color: params.color })
        } else if (v === 'MeshLambertMaterial') {
          cube.material = new MeshLambertMaterial({ color: params.color })
        } else if (v === 'MeshPhongMaterial') {
          const material = new MeshPhongMaterial()
          material.color.set(params.color) // 红色
          material.flatShading = true
          material.shininess = 130 // 高光
          material.needsUpdate = true
          cube.material = material
        }
      })

    gui
      .add(params, 'color', {
        red: 0xff0000,
        green: 0x00ff00,
        blue: 0x0000ff
      })
      .name('颜色')
      .onChange((v) => {
        (cube.material as MeshBasicMaterial).color.set(v)
      })

    addAnimationCallback((delta) => {
      cube.rotation.x += delta
      cube.rotation.y += delta * 0.5
    })
  }
})
</script>
<style scoped>
.el-link {
  margin-right: 10px;
}
</style>